# filepath: d:\CompanyProject\Gitee\DBCompareX\backend\app\routers\task_data_sync\setting.py
from fastapi import APIRouter, HTTPException, Body, Query, Depends
from typing import Optional, Dict, List

from ...models.task_data_sync.setting import TaskDataSyncSettingModel
from ...models.task_data_sync.execution import TaskDataSyncExecutionModel
from ...models.task_data_sync.scheduler import scheduler
from ...schemas.task_data_sync.setting import (
    TaskDataSyncSettingCreate, 
    TaskDataSyncSettingUpdate,
    TaskDataSyncSettingExecute,
    TaskDataSyncSettingUpdateStatus
)
from ...utils.response_utils import success_response, error_response
from ...routers.auth import get_current_user  # 引入用户认证依赖

router = APIRouter(prefix="/taskDataSyncSetting")

@router.post("/create")
async def create_task_data_sync_setting(
    task_data: TaskDataSyncSettingCreate = Body(...),
    current_user = Depends(get_current_user)
):
    """
    创建数据同步任务配置
    """
    try:
        # 创建任务配置
        result = await TaskDataSyncSettingModel.create(task_data.dict(), current_user.username)
        
        # 如果任务状态为启用，添加到调度器
        if task_data.status == 1:
            await scheduler.add_task(result)
        
        return success_response(data=result)
    except Exception as e:
        return error_response(message=f"创建数据同步任务配置失败: {str(e)}", code=500)

@router.post("/update")
async def update_task_data_sync_setting(
    task_data: TaskDataSyncSettingUpdate = Body(...),
    current_user = Depends(get_current_user)
):
    """
    更新数据同步任务配置
    """
    try:
        task_id = task_data.id
        
        # 获取原始任务配置
        old_task = await TaskDataSyncSettingModel.find_by_id(task_id)
        if not old_task:
            return error_response(message="未找到指定ID的数据同步任务配置", code=404)
        
        # 更新任务配置
        result = await TaskDataSyncSettingModel.update(task_id, task_data.dict(exclude_unset=True), current_user.username)
        
        # 更新调度器中的任务
        old_status = old_task.get("status", 0)
        new_status = task_data.status if task_data.status is not None else old_status
        
        # 如果状态从启用变为禁用
        if old_status == 1 and new_status == 0:
            await scheduler.remove_task(task_id)
        
        # 如果状态从禁用变为启用，或者已启用但其他参数发生变化
        elif new_status == 1:
            await scheduler.update_task(result)
        
        return success_response(data=result)
    except Exception as e:
        return error_response(message=f"更新数据同步任务配置失败: {str(e)}", code=500)

@router.post("/execute")
async def execute_task_data_sync_setting(
    task_data: TaskDataSyncSettingExecute = Body(...)
):
    """
    手动执行数据同步任务
    """
    try:
        task_id = task_data.id
        
        # 检查任务是否存在
        task = await TaskDataSyncSettingModel.find_by_id(task_id)
        if not task:
            return error_response(message="未找到指定ID的数据同步任务配置", code=404)
        
        # 执行任务
        result = await TaskDataSyncExecutionModel.execute_task(task_id)
        
        return success_response(data=result)
    except Exception as e:
        return error_response(message=f"执行数据同步任务失败: {str(e)}", code=500)

@router.post("/updatestatus")
async def update_task_data_sync_status(
    task_data: TaskDataSyncSettingUpdateStatus = Body(...),
    current_user = Depends(get_current_user)
):
    """
    修改数据同步任务状态
    
    将根据状态变化自动处理后台定时任务队列:
    - 禁用到启用: 任务将被加入到调度器
    - 启用到禁用: 任务将从调度器中移除
    """
    try:
        task_id = task_data.id
        new_status = task_data.status
        
        # 获取原始任务配置
        old_task = await TaskDataSyncSettingModel.find_by_id(task_id)
        if not old_task:
            return error_response(message="未找到指定ID的数据同步任务配置", code=404)
        
        old_status = old_task.get("status", 0)
        
        # 更新任务状态
        result = await TaskDataSyncSettingModel.update_status(task_id, new_status, current_user.username)
        
        # 更新调度器中的任务
        # 如果状态从启用变为禁用
        if old_status == 1 and new_status == 0:
            await scheduler.remove_task(task_id)
            
        # 如果状态从禁用变为启用
        elif old_status == 0 and new_status == 1:
            await scheduler.add_task(result)
        
        return success_response()
    except Exception as e:
        return error_response(message=f"更新数据同步任务状态失败: {str(e)}", code=500)

@router.get("/list")
async def list_task_data_sync_settings(
    status: Optional[int] = Query(None, description="状态 (0 禁用，1 启用)"),
    db_info_setting_id: Optional[str] = Query(None, description="数据库源配置ID"),
    table_name: Optional[str] = Query(None, description="表名"),
    task_name: Optional[str] = Query(None, description="任务名称")
):
    """
    查询数据同步任务配置列表
    """
    try:
        # 构建查询条件
        query = {}
        if status is not None:
            query["status"] = status
        if db_info_setting_id:
            query["db_info_setting_id"] = db_info_setting_id
        if table_name:
            query["table_name"] = table_name
        if task_name:
            query["task_name"] = task_name
            
        # 查询记录
        results = await TaskDataSyncSettingModel.find_all(query)
        
        return success_response(data=results)
    except Exception as e:
        return error_response(message=f"查询数据同步任务配置列表失败: {str(e)}", code=500)

@router.get("/info")
async def get_task_data_sync_setting(
    id: str = Query(..., description="数据同步任务配置ID")
):
    """
    根据ID查询数据同步任务配置
    """
    try:
        # 查询记录
        result = await TaskDataSyncSettingModel.find_by_id(id)
        
        if result:
            # 获取调度状态
            job_status = scheduler.get_job_status(id)
            result["job_status"] = job_status
            
            # 获取最近的执行日志
            execution_logs = await TaskDataSyncExecutionModel.get_execution_logs_by_task(id, limit=5)
            result["recent_executions"] = execution_logs
            
            return success_response(data=result)
        else:
            return error_response(message="未找到指定ID的数据同步任务配置", code=404)
    except Exception as e:
        return error_response(message=f"查询数据同步任务配置信息失败: {str(e)}", code=500)

@router.post("/delete")
async def delete_task_data_sync_setting(
    id: str = Body(..., embed=True),
    current_user = Depends(get_current_user)
):
    """
    删除数据同步任务配置
    将同时删除相关的详情和映射数据
    如果任务正在调度中，会先从调度器中移除
    """
    try:
        # 检查任务是否存在
        task = await TaskDataSyncSettingModel.find_by_id(id)
        if not task:
            return error_response(message="未找到指定ID的数据同步任务配置", code=404)
        
        # 如果任务正在调度中，先从调度器中移除
        if task.get("status") == 1:
            await scheduler.remove_task(id)
        
        # 删除任务及相关数据
        result = await TaskDataSyncSettingModel.delete_by_id(id)
        
        if result:
            return success_response(message="删除成功")
        else:
            return error_response(message="删除失败", code=500)
    except Exception as e:
        return error_response(message=f"删除数据同步任务失败: {str(e)}", code=500)